import React, { useState } from 'react';
import { Link, useLocation } from 'react-router-dom';

import './menu.scss'

const MenuItem = ({ item }) => {
  const location = useLocation();
  // 检查当前路径是否与菜单项匹配，以便应用活动状态样式
  const isActive = location.pathname.startsWith(`/${item.path}`);
  
  const [isOpen, setIsOpen] = useState(false);

  const toggleMenu = () => {
    setIsOpen(!isOpen);
  };

  if (item.children && item.children.length > 0) {
    return (
      <li className={`nav-item ${isActive ? 'active' : ''}`}>
        <a 
          className="nav-link has-submenu" 
          href="#" 
          onClick={toggleMenu}
        >
          <i className={`icon-${item.meta.icon}`}></i>
          {item.meta.title}
          <span className={`submenu-toggle-icon ${isOpen ? 'open' : ''}`}>▾</span>
        </a>
        <ul className={`sub-menu ${isOpen ? 'open' : ''}`}>
          {item.children.map((child, index) => (
            <MenuItem key={index} item={child} />
          ))}
        </ul>
      </li>
    );
  }

  return (
    <li className={`nav-item ${isActive ? 'active' : ''}`}>
      <Link to={`/${item.path}`} className="nav-link">
        <i className={`icon-${item.meta.icon}`}></i>
        {item.meta.title}
      </Link>
    </li>
  );
};

const MenuList = ({ menuData }) => {
  return (
    <ul className="nav-menu">
      {menuData.map((item, index) => (
        <MenuItem key={index} item={item} />
      ))}
    </ul>
  );
};

export default MenuList;